package com.google.sydym6.logic.database;

import java.util.Map.Entry;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class TableWorker implements ITableWorker {

	private String tableName;
	
	public TableWorker(String tableName) {
		this.tableName = tableName;
	}

	@Override
	public boolean insert(ContentValues values) {
		long result = TableFactory.getDataBase().insert(tableName, null, values);
		Log.v("database", "Inserting result code: " + result);
		Cursor cursor = selectAll();
		Log.v("database", "Selected rows: " + cursor.getCount());
		cursor.moveToFirst();
		Log.v("database", "Radio name: " + cursor.getString(1));
		Log.v("database", "Song artist: " + cursor.getString(2));
		Log.v("database", "Song title: " + cursor.getString(3));
		return false;
	}

	@Override
	public boolean delete(String key, String[] values) {
		return TableFactory.getDataBase().delete(tableName, key + "=?", values) > 0;
	}

	/**
	 * @deprecated
	 */
	@Override
	public Cursor select(String[] names, String[] values) {
		String query = "SELECT * FROM " + tableName + " WHERE ";
		
		for(int i = 0; i < names.length; i++) {
			query += names[i] + " = '" + values[i] + "'";
			if (i != names.length - 1)
				query += " AND ";
		}
		
		Cursor cursor = TableFactory.getDataBase().rawQuery(query, null);
		return cursor;
	}
	
	@Override
	public Cursor select(ContentValues values) {

		String query = "SELECT * FROM " + tableName + " WHERE ";
		int length = values.size();
		int index = 0;
		for(Entry<String, Object> i : values.valueSet()) {
			query += i.getKey() + " = '" + i.getValue().toString() + "'";
			if (index != length - 1)
				query += " AND ";
			index++;
		}
		
		Cursor cursor = TableFactory.getDataBase().rawQuery(query, null);
		return cursor;
	}

	@Override
	public Cursor selectAll() {
		return TableFactory.getDataBase().rawQuery("SELECT * FROM " + tableName, null);
	}

	@Override
	public boolean update(ContentValues targetValues, String key, String[] values) {
		return TableFactory.getDataBase().update(tableName, targetValues, key + "=?", values) > 0;
	}
}
